#!/usr/bin/env node
/**
 * Phase产物完整性验证脚本
 * 用法：node scripts/validate-phase-artifacts.js ComponentName [PhaseN]
 *
 * 遵循 CONTRIBUTING.md 规范和 phase-manifest.json 定义
 * 实施分析报告建议1: 强制检查点验证
 */

const fs = require('fs');
const path = require('path');

/**
 * 加载 phase-manifest.json
 */
function loadManifest() {
  const manifestPath = path.join(__dirname, '../Workflow/FigmaMCPWorkflow/phase-manifest.json');

  if (!fs.existsSync(manifestPath)) {
    throw new Error(`phase-manifest.json 未找到: ${manifestPath}`);
  }

  return JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
}

/**
 * 解析产物路径模板
 */
function resolveArtifactPath(template, componentName, root) {
  // 替换 {ComponentName} 或 {PanelType} 占位符
  const resolved = template
    .replace('{ComponentName}', componentName)
    .replace(/{PanelType}/g, '*');  // 使用通配符匹配

  return path.join(root, componentName, resolved);
}

/**
 * 检查文件是否存在（支持通配符）
 */
function fileExists(filePath) {
  if (filePath.includes('*')) {
    // 通配符路径：检查目录是否存在
    const dir = path.dirname(filePath);
    return fs.existsSync(dir);
  }
  return fs.existsSync(filePath);
}

/**
 * 验证单个 Phase 产物完整性
 */
function validatePhaseArtifacts(phaseName, componentName, manifest, root) {
  console.log(`\n📋 验证 ${phaseName} 产物完整性...`);

  const phaseConfig = manifest.phases[phaseName];
  if (!phaseConfig) {
    throw new Error(`Phase ${phaseName} 在 manifest 中未定义`);
  }

  const requiredFiles = phaseConfig.outputs.intermediate
    .filter(f => f.required === true)
    .map(f => ({
      path: f.path,
      description: f.description
    }));

  console.log(`  必需产物数量: ${requiredFiles.length}`);

  const results = {
    phase: phaseName,
    total: requiredFiles.length,
    existing: 0,
    missing: [],
    warnings: []
  };

  requiredFiles.forEach(file => {
    const resolvedPath = resolveArtifactPath(file.path, componentName, root);
    const exists = fileExists(resolvedPath);

    if (exists) {
      results.existing++;
      console.log(`  ✅ ${file.path}`);
    } else {
      results.missing.push({
        path: file.path,
        description: file.description,
        resolvedPath
      });
      console.log(`  ❌ ${file.path} (缺失)`);
    }
  });

  // 检查 system 注册文件
  if (phaseConfig.outputs.system) {
    phaseConfig.outputs.system.forEach(sysFile => {
      if (sysFile.required) {
        const resolvedPath = resolveArtifactPath(sysFile.path, componentName, root);
        const exists = fileExists(resolvedPath);

        if (exists) {
          console.log(`  ✅ [系统注册] ${sysFile.path}`);
        } else {
          results.missing.push({
            path: sysFile.path,
            description: sysFile.description,
            resolvedPath,
            type: 'system'
          });
          console.log(`  ❌ [系统注册] ${sysFile.path} (缺失)`);
        }
      }
    });
  }

  // 检查 checkpoint
  const checkpointPath = phaseConfig.outputs.checkpoints?.[0]?.path;
  if (checkpointPath) {
    const resolvedCheckpoint = resolveArtifactPath(checkpointPath, componentName, root);
    if (fileExists(resolvedCheckpoint)) {
      console.log(`  ✅ [Checkpoint] ${checkpointPath}`);

      // 验证 checkpoint 内容与实际产物一致性
      try {
        const checkpoint = JSON.parse(fs.readFileSync(resolvedCheckpoint, 'utf8'));
        const declaredArtifacts = checkpoint.output?.artifacts || [];
        const existingArtifacts = [];
        const missingArtifacts = [];

        declaredArtifacts.forEach(artifact => {
          const artifactPath = path.join(root, componentName, artifact);
          if (fs.existsSync(artifactPath)) {
            existingArtifacts.push(artifact);
          } else {
            missingArtifacts.push(artifact);
            results.warnings.push({
              type: 'checkpoint_mismatch',
              message: `Checkpoint声明产物存在但实际缺失: ${artifact}`
            });
          }
        });

        // 记录一致性指标
        const completeness = declaredArtifacts.length > 0
          ? existingArtifacts.length / declaredArtifacts.length
          : 1;

        if (completeness < 1) {
          console.log(`  ⚠️  Checkpoint一致性: ${(completeness * 100).toFixed(0)}% (${existingArtifacts.length}/${declaredArtifacts.length})`);
          results.warnings.push({
            type: 'checkpoint_consistency',
            message: `Checkpoint产物完整性: ${(completeness * 100).toFixed(0)}%`,
            details: {
              declared: declaredArtifacts.length,
              existing: existingArtifacts.length,
              missing: missingArtifacts.length,
              missingFiles: missingArtifacts
            }
          });
        }
      } catch (e) {
        results.warnings.push({
          type: 'checkpoint_parse_error',
          message: `Checkpoint解析失败: ${e.message}`
        });
      }
    } else {
      results.missing.push({
        path: checkpointPath,
        description: 'Phase checkpoint',
        resolvedPath: resolvedCheckpoint,
        type: 'checkpoint'
      });
      console.log(`  ❌ [Checkpoint] ${checkpointPath} (缺失)`);
    }
  }

  results.completeness = results.total > 0 ? results.existing / results.total : 0;

  return results;
}

/**
 * 验证所有 Phase 或指定 Phase
 */
function validateArtifacts(componentName, specificPhase = null) {
  const root = process.cwd();
  const manifest = loadManifest();

  console.log(`\n🔍 Phase产物完整性验证`);
  console.log(`  组件: ${componentName}`);
  console.log(`  manifest 版本: ${manifest.metadata.version}`);

  const phasesToValidate = specificPhase
    ? [specificPhase]
    : ['Phase0', 'Phase1', 'Phase2', 'Phase3', 'Phase4', 'Phase5'];

  const allResults = {};

  phasesToValidate.forEach(phase => {
    try {
      allResults[phase] = validatePhaseArtifacts(phase, componentName, manifest, root);
    } catch (error) {
      console.error(`\n❌ ${phase} 验证失败: ${error.message}`);
      allResults[phase] = { error: error.message };
    }
  });

  // 生成汇总报告
  console.log(`\n` + '='.repeat(60));
  console.log(`📊 验证汇总`);
  console.log('='.repeat(60));

  let totalRequired = 0;
  let totalExisting = 0;
  const allMissing = [];
  const allWarnings = [];

  Object.entries(allResults).forEach(([phase, result]) => {
    if (result.error) {
      console.log(`${phase}: ❌ 验证失败`);
      return;
    }

    totalRequired += result.total;
    totalExisting += result.existing;
    allMissing.push(...result.missing.map(m => ({ phase, ...m })));
    allWarnings.push(...result.warnings.map(w => ({ phase, ...w })));

    const status = result.completeness === 1 ? '✅' : '⚠️ ';
    console.log(
      `${phase}: ${status} ${result.existing}/${result.total} (${(result.completeness * 100).toFixed(0)}%)`
    );
  });

  const overallCompleteness = totalRequired > 0 ? totalExisting / totalRequired : 0;

  console.log('='.repeat(60));
  console.log(`总计: ${totalExisting}/${totalRequired} (${(overallCompleteness * 100).toFixed(1)}%)`);

  if (allMissing.length > 0) {
    console.log(`\n❌ 缺失产物清单 (${allMissing.length}):`);
    allMissing.forEach(m => {
      console.log(`  - [${m.phase}] ${m.path}`);
      if (m.description) {
        console.log(`    说明: ${m.description}`);
      }
    });
  }

  if (allWarnings.length > 0) {
    console.log(`\n⚠️  警告 (${allWarnings.length}):`);
    allWarnings.forEach(w => {
      console.log(`  - [${w.phase}] ${w.message}`);
    });
  }

  // 保存验证报告
  const reportDir = path.join(root, componentName, 'validation-reports');
  if (!fs.existsSync(reportDir)) {
    fs.mkdirSync(reportDir, { recursive: true });
  }

  const reportPath = path.join(reportDir, 'artifact-validation-report.json');
  const report = {
    timestamp: new Date().toISOString(),
    componentName,
    manifestVersion: manifest.metadata.version,
    overallCompleteness,
    totalRequired,
    totalExisting,
    phaseResults: allResults,
    missing: allMissing,
    warnings: allWarnings
  };

  fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
  console.log(`\n📄 验证报告已保存: ${reportPath}`);

  // 判断是否通过
  const passed = overallCompleteness >= 0.8; // 80%阈值
  if (passed) {
    console.log(`\n✅ 产物完整性验证通过 (${(overallCompleteness * 100).toFixed(1)}% >= 80%)`);
    return 0;
  } else {
    console.log(`\n❌ 产物完整性验证失败 (${(overallCompleteness * 100).toFixed(1)}% < 80%)`);
    console.log(`   建议: 补充缺失产物后重新验证`);
    return 1;
  }
}

// CLI 执行
function main() {
  const componentName = process.argv[2];
  const specificPhase = process.argv[3];

  if (!componentName) {
    console.error('❌ 缺少组件名称');
    console.error('用法: node scripts/validate-phase-artifacts.js ComponentName [PhaseN]');
    console.error('示例: node scripts/validate-phase-artifacts.js UsageTrendsProd2');
    console.error('     node scripts/validate-phase-artifacts.js UsageTrendsProd2 Phase2');
    process.exit(1);
  }

  try {
    const exitCode = validateArtifacts(componentName, specificPhase);
    process.exit(exitCode);
  } catch (error) {
    console.error(`\n❌ 验证失败: ${error.message}`);
    console.error(error.stack);
    process.exit(1);
  }
}

main();
